package com.app.megaprosoft.modyimcarcare;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;

import com.app.megaprosoft.DB.Ar;
import com.app.megaprosoft.DB.ArGroup;
import com.app.megaprosoft.DB.ArGroupMain;
import com.app.megaprosoft.DB.CarBand;
import com.app.megaprosoft.DB.CarColor;
import com.app.megaprosoft.DB.CarGeneration;
import com.app.megaprosoft.DB.CarGroup;
import com.app.megaprosoft.DB.FFUser;
import com.app.megaprosoft.DB.Province;
import com.app.megaprosoft.DB.ServicePOS;
import com.app.megaprosoft.DB.UserGroup;
import com.app.megaprosoft.general.DateTime;
import com.app.megaprosoft.modyimcarcare.Carcare_Login.LoadingLogin;
import com.megaprosoft.modyimcarcare.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class CarCare_GetCar extends Activity {
	
	// Animation
	private Animation shake;
	
	// Dialog
	public static final int 	DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog 		mProgressDialog;
	private AlertDialog 		PhoneDialog;
	// Button
	private Button 			 searchcar_button_enter
							,searchcar_button_cancle
							,searchcar_button_clr
							,searchcar_button_new
							,searchcar_button_import
							,bt_ar_general
							,bt_ar_member;
	private	Bitmap 			 bImage;
	private	ImageView		 imgUser;
	private ImageButton 	 bt_ar_buttontime
							,bt_wait;
	
	// Array 
	private TextView 	 	 tv_idcar
							,tv_idar
							,tv_arname
							,tv_arphone
							,tv_argroup
							,tv_ar_province
//							,tv_cartype
							,tv_cargroup
							,tv_carsize
							,tv_carband
							,tv_cargen
							,tv_carcolor
							,tv_idservice
							,tv_timewait
							,tv_edit
							,tv_new
							,tv_callnumber;

	// String
	private String 			 _argroup[][]
							,_provinc_favorit[][]
							,_provinc_defalt[][]
							,_cargroup[][]
							,_carbands_favorit[][]
							,_carbands_defalt[][]
							,_cargenerations[][]
							,_carcolor[][];
	private Button 			button_1,button_2,button_3,button_4,button_5,
							button_6,button_7,button_8,button_9,button_0,
							button_clrsr,button_cancle,button_enter,button_del;
	private String 			MODE;
	
	private String 			ArGroupMainOID 		="",
							ArGroupOID     		="",
							CarGroupOID			="",	
							CarBandOID			="",
							CarGenerationOID	="",
							CarColorOID			="",
							ArCode				="", 
							ArTitle				="", 
							ArName				="ไม่ระบุ", 
							ArNickName			="ไม่ระบุ",
							ArGroupDesc			="",
							FFUserName			="ไม่ระบุ",
							ArGroupMainCode		="",
							ArGroupMainDesc		="",
							ProvinceCode		="",
							ProvinceName		="ไม่ระบุ", 
							ArStatus 			="",
							ArGroupCode			="", 
						
							Telephone			="", 
							Mobile				="",
							FFSaleCode			="", 
							FFUserCode			="", 
							
							PicPath				="", 
							FFCashier			="", 
							VehicleRegistration	="", 
							CarType				="",
							ColorOID			="", 
							CarSize				="",
							CompanyOID			="", 
							FFUserOID			="", 
							DepCode				="",
							UserGroupOID		="", 
							
							TabletCode			="",
							POSDocOID			="", 
						
							CarGenerationName	="ไม่ระบุ",
							ColorName			="ไม่ระบุ",
							CarGroupName		="ไม่ระบุ",
							CarBandName			="ไม่ระบุ",
							
							Datetimenow			="",
							OID					="",
							PayableDateTime 	="",
							UserGroupCode		="",
							AROID				=""
							;

	
	// Boolean
	private Boolean 		Ismember = false;
	private Boolean 		IsinsertService = false;
	private Boolean 		IsinsertAr = false;
	private Boolean 		Iswait = true;
	private Boolean 		Isedit = false;
	private Boolean 		change =false;
	
	
	// Dialog
	private AlertDialog 	DataDialog,
							ImportDialog;
	private int 			DATACASE;
	private int				 datacase_idar		= 0
							,datacase_idcar		= 1
							,datacase_arname 	= 2
							,datacase_arphone  	= 3
							,datacase_argroup  	= 4
							,datacase_provinec  = 5
							,datacase_cartype   = 6
							,datacase_cargroup  = 7
							,datacase_carsize   = 8
							,datacase_carband   = 9
						    ,datacase_cargen    = 10
						    ,datacase_carcolor  = 11;
	private ListView 		lv;
	private EditText 		et;
	private Button 	 		bt;
	private String 			datasearch[][];
	private ArrayAdapter<String>
							mArrayAdapter;
	private int 			textlength = 0;
	
	// Function
	DateTime datetime = new DateTime();
		
	Ar ar = new Ar();
	UserGroup usergroup = new UserGroup();
	ServicePOS servicepos = new ServicePOS();
	FFUser ffuser = new FFUser();
	ArGroupMain argroupMain = new ArGroupMain();
	ArGroup argroup = new ArGroup();
	Province province = new Province();
	CarGroup cargroup = new CarGroup();
	CarBand carband = new CarBand();
	CarGeneration cargenneration = new CarGeneration();
	CarColor carcolor = new CarColor();
	
	Carcare_SessionManagement 				session;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("ใบรับบริการ ศูนย์เอาใจใส่รถยนต์มดขยัน");
		setContentView(R.layout.a_carcare_activity_getcar);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		
		//  Button
		searchcar_button_enter = (Button) findViewById(R.id.a_searchcar_button_enter);
		searchcar_button_enter.setOnClickListener(searchcar_enter);
		searchcar_button_cancle = (Button) findViewById(R.id.a_searchcar_button_cancle);
		searchcar_button_cancle.setOnClickListener(searchcar_cancle);
		searchcar_button_clr = (Button) findViewById(R.id.a_searchcar_button_clrscr);
		searchcar_button_clr.setOnClickListener(searchcar_clr);
		searchcar_button_import = (Button) findViewById(R.id.button_importAr);
		searchcar_button_import.setOnClickListener(importcar);
		tv_timewait = (TextView) findViewById(R.id.a_getcar_tv_time);
		tv_idservice = (TextView) findViewById(R.id.a_getcar_tv_iddoc);
		bt_ar_buttontime = (ImageButton) findViewById(R.id.bt_ar_buttontime);
		bt_ar_buttontime.setOnClickListener(timewait);
		bt_wait = (ImageButton) findViewById(R.id.bt_ar_buttonwait);
		bt_wait.setOnClickListener(timenotwait);
		imgUser = (ImageView) findViewById(R.id.imguser);
		
		bt_ar_general = (Button) findViewById(R.id.a_getCar_bt_general);
		bt_ar_member = (Button) findViewById(R.id.a_getCar_bt_member);
		bt_ar_member.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setDATACASE(datacase_idar);
				DataDialog.show();
			}
		});
		tv_edit = (TextView) findViewById(R.id.txtEditable);
		tv_new = (TextView) findViewById(R.id.txtNewable);
		tv_arname = (TextView) findViewById(R.id.a_getcar_et_arname);
		tv_arname.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_arname);
				DataDialog.show();
			}
		});
		tv_arphone = (TextView) findViewById(R.id.a_getcar_et_phonnumber);
		tv_arphone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
//				setDATACASE(datacase_arphone);
//				DataDialog.show();
				PhoneDialog.show();
			}
		});
		tv_argroup = (TextView) findViewById(R.id.a_getcar_sp_argroup);
		tv_argroup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_argroup);
				DataDialog.show();
			}
		});
		
		tv_cargroup = (TextView) findViewById(R.id.a_getcar_sp_cargroup);
		tv_cargroup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_cargroup);
				DataDialog.show();
			}
		});
		tv_carband = (TextView) findViewById(R.id.a_getcar_sp_carband);
		tv_carband.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_carband);
				DataDialog.show();
			}
		});
		tv_cargen = (TextView) findViewById(R.id.a_getcar_sp_generation);
		tv_cargen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_cargen);
				DataDialog.show();
			}
		});
		tv_carcolor = (TextView) findViewById(R.id.a_getcar_sp_color);
		tv_carcolor.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_carcolor);
				DataDialog.show();
			}
		});
		tv_idcar = (TextView) findViewById(R.id.a_getCar_et_idcar);
		tv_idcar.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					setDATACASE(datacase_idcar);
					DataDialog.show();
				}
		});
		tv_idar = (TextView) findViewById(R.id.a_getcar_et_idar);
		tv_idar.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					setDATACASE(datacase_idar);
					DataDialog.show();
				}
		});
			
		// Image Button
		tv_argroup = (TextView) findViewById(R.id.a_getcar_sp_argroup);
		tv_argroup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_argroup);
				DataDialog.show();
			}
		});
		tv_ar_province = (TextView) findViewById(R.id.a_getcar_sp_province);
		tv_ar_province.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_provinec);
				DataDialog.show();
			}
		});
//		tv_cartype = (TextView) findViewById(R.id.a_getcar_cartype);
//		tv_cartype.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				setDATACASE(datacase_cartype);
//				DataDialog.show();
//			}
//		});
		tv_carsize = (TextView) findViewById(R.id.a_getcar_carsize);
		tv_carsize.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				setDATACASE(datacase_carsize);
				DataDialog.show();
			}
		});
		
		session = new Carcare_SessionManagement(getApplicationContext());
		session.checkLogin();
        HashMap<String, String> user = session.getUserDetails();

        setFFUserCode(user.get(Carcare_SessionManagement.KEY_FFUserOID));
        setFFUserName(user.get(Carcare_SessionManagement.KEY_UserName));
        setDepCode(user.get(Carcare_SessionManagement.KEY_DepCode));
        setUserGroupOID(user.get(Carcare_SessionManagement.KEY_UserGroupOID));
        setUserGroupCode(user.get(Carcare_SessionManagement.KEY_UserGroupCode));
        setPicPath(user.get(Carcare_SessionManagement.KEY_PicPath));
        setTabletCode(user.get(Carcare_SessionManagement.KEY_TabletCode));
        
//        Toast.makeText(getApplicationContext(), getUserGroupCode(), Toast.LENGTH_SHORT).show();     
        
		Bundle bundle = getIntent().getExtras();
		
		ar.setContext(getApplicationContext());
		servicepos.setContext(getApplicationContext());
		ffuser.setContext(getApplicationContext());
		argroupMain.setContext(getApplicationContext());
		argroup.setContext(getApplicationContext());
		province.setContext(getApplicationContext());
		cargroup.setContext(getApplicationContext());
		carband.setContext(getApplicationContext());
		cargenneration.setContext(getApplicationContext());
		carcolor.setContext(getApplicationContext());
		usergroup.setContext(getApplicationContext());
		
		if (bundle != null) {
			
			MODE = (String) bundle.get("MODE");
			
			if(MODE.equals("EDIT")){
				
				tv_new.setVisibility(View.GONE);
				tv_edit.setVisibility(View.VISIBLE);
				Ismember=true;
				setPOSDocOID((String) bundle.get("ServiceId"));
				try{
					String data[][] = servicepos.SelectAll_ServicePOS("", getPOSDocOID(), "");
					setVehicleRegistration(data[0][2]);
					tv_idcar.setText(getVehicleRegistration());
					setArCode(data[0][3]);
					tv_idar.setText(data[0][3]);
					tv_idar.setTextColor(Color.BLUE);
					tv_idservice.setText(getPOSDocOID());
					tv_idservice.setTextColor(Color.BLUE);
					setPayableDateTime(data[0][6]);
					if(!getPayableDateTime().equals("00:00")){
						tv_timewait.setText(getPayableDateTime());
						tv_timewait.setEnabled(true);
					}
					
					datasearch = ar.SelectAll_ArFF( "",getArCode(),"");
					setAROID(datasearch[0][0]);
					setArCode(datasearch[0][1]);
					tv_idar.setText(datasearch[0][1]);
					setArGroupMainOID(datasearch[0][22]);
					setArGroupMainCode(datasearch[0][23]);
					setArGroupMainDesc(datasearch[0][24]);
					if(getArGroupMainOID().equals("116201309160002")){
						Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.vipmember);
						imgUser.setImageBitmap(bImage);
						imgUser.setScaleType(ScaleType.FIT_XY);
						bt_ar_general.setBackgroundResource(R.drawable.black);
						bt_ar_member.setBackgroundResource(R.drawable.green_regiscar);
					}else{
						Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.logouser);
						imgUser.setImageBitmap(bImage);
						imgUser.setScaleType(ScaleType.FIT_XY);
						bt_ar_general.setBackgroundResource(R.drawable.green_regiscar);
						bt_ar_member.setBackgroundResource(R.drawable.black);
					}
					setArGroupOID(datasearch[0][19]);
					setArGroupDesc(datasearch[0][21]);
					
					tv_argroup.setText(getArGroupDesc());
					setProvinceCode(datasearch[0][12]);
					setProvinceName(datasearch[0][13]);
					tv_ar_province.setText(getProvinceName());
					setTelephone(datasearch[0][16]);
					tv_arphone.setText(getTelephone());
					setArName(datasearch[0][4]);
					tv_arname.setText(datasearch[0][4]);
					setVehicleRegistration(datasearch[0][55]);
					tv_idcar.setText(getVehicleRegistration());
					
					setCarGroupOID(datasearch[0][63]);
					setCarGroupName(datasearch[0][64]);
					tv_cargroup.setText(getCarGroupName());
					setCarSize(datasearch[0][60]);
					tv_carsize.setText(getCarSize());
					
					setCarBandOID(datasearch[0][54]);
					setCarBandName(datasearch[0][56]);
					
					tv_carband.setText(getCarBandName());
					
					setCarGenerationOID(datasearch[0][57]);
					setCarGenerationName(datasearch[0][61]); 
					tv_cargen.setText(getCarGenerationName());
					
					setCarColorOID(datasearch[0][59]);
					setColorName(datasearch[0][62]);
					tv_carcolor.setText(getColorName());
					
					setCarType(datasearch[0][58]);
						
				}catch(Exception e){
					Toast.makeText(getApplicationContext(),"ERROR",Toast.LENGTH_SHORT).show();	
				}
				
			}else{
				tv_new.setVisibility(View.VISIBLE);
				tv_edit.setVisibility(View.GONE);
			}
		}
		
		LayoutInflater inflater = CarCare_GetCar.this.getLayoutInflater();
		
		PhoneDialog = new AlertDialog.Builder(CarCare_GetCar.this)
        .setView(inflater.inflate(R.layout.a_carcare_dialog_phon, null))
        .setCancelable(false)
        .create();
        
		PhoneDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
				
				tv_callnumber = (TextView) PhoneDialog.findViewById(R.id.a_login_password);
				tv_callnumber.setText(tv_arphone.getText().toString());
				
				button_0 = (Button) PhoneDialog.findViewById(R.id.a_login_button0);
				button_0.setOnClickListener(text_0);
				button_1 = (Button) PhoneDialog.findViewById(R.id.a_login_button1);
				button_1.setOnClickListener(text_1);
				button_2 = (Button) PhoneDialog.findViewById(R.id.a_login_button2);
				button_2.setOnClickListener(text_2);
				button_3 = (Button) PhoneDialog.findViewById(R.id.a_login_button3);
				button_3.setOnClickListener(text_3);
				button_4 = (Button) PhoneDialog.findViewById(R.id.a_login_button4);
				button_4.setOnClickListener(text_4);
				button_5 = (Button) PhoneDialog.findViewById(R.id.a_login_button5);
				button_5.setOnClickListener(text_5);
				button_6 = (Button) PhoneDialog.findViewById(R.id.a_login_button6);
				button_6.setOnClickListener(text_6);
				button_7 = (Button) PhoneDialog.findViewById(R.id.a_login_button7);
				button_7.setOnClickListener(text_7);
				button_8 = (Button) PhoneDialog.findViewById(R.id.a_login_button8);
				button_8.setOnClickListener(text_8);
				button_9 = (Button) PhoneDialog.findViewById(R.id.a_login_button9);
				button_9.setOnClickListener(text_9);
				button_clrsr = (Button) PhoneDialog.findViewById(R.id.a_login_button_clrscr);
				button_clrsr.setOnClickListener(text_clrsr);
				button_enter = (Button) PhoneDialog.findViewById(R.id.a_login_button_enter);
				button_enter.setOnClickListener(text_enter);
				button_cancle = (Button) PhoneDialog.findViewById(R.id.a_login_button_cancle);
				button_cancle.setOnClickListener(text_cancle);
				button_del = (Button) PhoneDialog.findViewById(R.id.a_login_button_del);
				button_del.setOnClickListener(text_del);
				
			}
		});
        
		DataDialog = new AlertDialog.Builder(CarCare_GetCar.this)
        .setView(inflater.inflate(R.layout.a_carcare_activity_search, null))
        .setCancelable(true)
        .create();
		
		 ImportDialog = new AlertDialog.Builder(CarCare_GetCar.this)
        .setView(inflater.inflate(R.layout.a_carcare_activity_import, null))
        .setCancelable(true)
        .create();
		
		 DataDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {		
				lv = (ListView) DataDialog.findViewById(R.id.ListView0111);
				et = (EditText) DataDialog.findViewById(R.id.EditText0111);
				bt = (Button) DataDialog.findViewById(R.id.button1);
				et.setText("");
				et.setVisibility(View.VISIBLE);
				bt.setVisibility(View.VISIBLE);
				final InputMethodManager imm = (InputMethodManager)getSystemService(
					      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
				mArrayAdapter = new ArrayAdapter<String>(CarCare_GetCar.this, android.R.layout.simple_list_item_1);
				lv.setAdapter(mArrayAdapter);
				switch (getDATACASE()) {
				case 0:
					// datacase_idar
					et.setText("");
					et.setHint("รหัสลูกค้า");
					break;
				case 1:
					// datacase_idcar
					
					et.setText(tv_idcar.getText().toString());
					et.setHint("หมายเลขทะเบียนรถ");
					break;
				case 2:
					// datacase_arname
					et.setHint("ชื่อลูกค้า");
					et.setText(tv_arname.getText().toString());
					break;
				case 3:
					// datacase_arphone
					et.setHint("เบอร์โทรศัพท์");
					et.setText(tv_arphone.getText().toString());
					break;
				case 4:
					// datacase_argroup
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					try {
						_argroup = argroup.SelectAll_ArGroup(getArGroupMainOID());
						int length = _argroup.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_argroup[i][2].toString());
						}
					} catch (Exception e) {
					}
					break;
				case 5:
					// datacase_provinec
					change = false;
					et.setHint(tv_ar_province.getText().toString());
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					try {
						_provinc_favorit = province.SelectAll_Addresses("1");
						int length = _provinc_favorit.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_provinc_favorit[i][2].toString());
						}
						mArrayAdapter.add("-------------------------------");
						_provinc_defalt = province.SelectAll_Addresses("0");
						length = _provinc_defalt.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_provinc_defalt[i][2].toString());
						}
					} catch (Exception e) {
					}
					break;
				case 6:
//					et.setVisibility(View.GONE);
//					bt.setVisibility(View.GONE);
////					et.setHint(tv_cartype.getText().toString());
//					mArrayAdapter.add("รถยนต์");
//					mArrayAdapter.add("รถมอเตอร์ไซต์");
					break;
				case 7:
					// datacase_cargroup
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					try {
						_cargroup = cargroup.SelectAll_CarGroup();
						int length = _cargroup.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_cargroup[i][1].toString());
						}
					}catch (Exception e) {
					}
					break;
				case 8:
					// datacase_carsize
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					et.setHint(tv_carsize.getText().toString());
					mArrayAdapter.add("S");
					mArrayAdapter.add("M");
					mArrayAdapter.add("L");
					mArrayAdapter.add("XL");
					break;
				case 9:
					// datacase_carband
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					et.setHint(tv_carband.getText().toString());
					try {
						_carbands_favorit = carband.SelectAll_CarBands("");
						int length = _carbands_favorit.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_carbands_favorit[i][2].toString());
						}
						mArrayAdapter.add("--------------");
						_carbands_defalt = carband.SelectAll_CarBands("999");
						length = _carbands_defalt.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_carbands_defalt[i][2].toString());
						}
					} catch (Exception e1) {
					}
					break;
				case 10:
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					// datacase_cargen
					et.setHint(tv_cargen.getText().toString());
					try {
						_cargenerations = cargenneration.SelectAll_CarGenerations(getCarGroupOID()
								.toString(), getCarBandOID().toString());
						int length = _cargenerations.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_cargenerations[i][2].toString());
						}
						
					} catch (Exception e) {
						mArrayAdapter.add("ไม่ระบุ");
					}
					break;
				case 11:
					// datacase_carcolor
					et.setHint(tv_carcolor.getText().toString());
					et.setVisibility(View.GONE);
					bt.setVisibility(View.GONE);
					try {
						_carcolor = carcolor.SelectAll_Colors();
						int length = _carcolor.length;
						for (int i = 0; i < length; i++) {
							mArrayAdapter.add(_carcolor[i][2].toString());
						}
					} catch (Exception e) {
					}
					break;
				default:
					break;
 
				}
				
				lv.setOnItemClickListener(new OnItemClickListener() {
					
					@Override
					public void onItemClick(AdapterView<?> arg0, View selectedItemView, int position,
							long id) {
						
						switch (getDATACASE()) {
						case 0:
							// datacase_idar
							tv_new.setVisibility(View.GONE);
							tv_edit.setVisibility(View.VISIBLE);
							Ismember = true;
							tv_idar.setText(datasearch[position][1]);
							setAROID(datasearch[0][0]);
							setArCode(datasearch[0][1]);
							setArGroupMainOID(datasearch[0][22]);
							setArGroupMainCode(datasearch[0][23]);
							setArGroupMainDesc(datasearch[0][24]);
							if(getArGroupMainOID().equals("116201309160002")){
								bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.vipmember);
								imgUser.setImageBitmap(bImage);
								imgUser.setScaleType(ScaleType.FIT_XY);
								bt_ar_general.setBackgroundResource(R.drawable.black);
								bt_ar_member.setBackgroundResource(R.drawable.green_regiscar);
							}else{
								bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.logouser);
								imgUser.setImageBitmap(bImage);
								imgUser.setScaleType(ScaleType.FIT_XY);
								bt_ar_general.setBackgroundResource(R.drawable.green_regiscar);
								bt_ar_member.setBackgroundResource(R.drawable.black);
							}
							setArGroupOID(datasearch[position][19]);
							setArGroupDesc(datasearch[position][21]);
							
							tv_argroup.setText(getArGroupDesc());
							setProvinceCode(datasearch[position][12]);
							setProvinceName(datasearch[position][13]);
							tv_ar_province.setText(getProvinceName());
							setTelephone(datasearch[position][16]);
							tv_arphone.setText(getTelephone());
							setArName(datasearch[position][4]);
							tv_arname.setText(datasearch[position][4]);
							setVehicleRegistration(datasearch[position][55]);
							tv_idcar.setText(getVehicleRegistration());
							
							setCarGroupOID(datasearch[position][63]);
							setCarGroupName(datasearch[position][64]);
							tv_cargroup.setText(getCarGroupName());
							setCarSize(datasearch[position][60]);
							tv_carsize.setText(getCarSize());
							
							setCarBandOID(datasearch[position][54]);
							setCarBandName(datasearch[position][56]);
							
							tv_carband.setText(getCarBandName());
							
							setCarGenerationOID(datasearch[position][57]);
							setCarGenerationName(datasearch[position][61]); 
							tv_cargen.setText(getCarGenerationName());
							
							setCarColorOID(datasearch[position][59]);
							setColorName(datasearch[position][62]);
							tv_carcolor.setText(getColorName());
							
							setCarType(datasearch[position][58]);
							
							break;
						case 1:
							tv_new.setVisibility(View.GONE);
							tv_edit.setVisibility(View.VISIBLE);
							Ismember = true;
							// datacase_icar
							if(MODE.equals("EDIT")){
								if(!et.getText().toString().equals("")){
									tv_idcar.setText(et.getText().toString());
									setVehicleRegistration(et.getText().toString());
								}
							}else{
								tv_idar.setText(datasearch[position][1]);
								setAROID(datasearch[0][0]);
								setArGroupMainOID(datasearch[0][22]);
								setArGroupMainCode(datasearch[0][23]);
								setArGroupMainDesc(datasearch[0][24]);
								if(getArGroupMainOID().equals("116201309160002")){
									bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.vipmember);
									imgUser.setImageBitmap(bImage);
									imgUser.setScaleType(ScaleType.FIT_XY);
									bt_ar_general.setBackgroundResource(R.drawable.black);
									bt_ar_member.setBackgroundResource(R.drawable.green_regiscar);
								}else{
									bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.logouser);
									imgUser.setImageBitmap(bImage);
									imgUser.setScaleType(ScaleType.FIT_XY);
									bt_ar_general.setBackgroundResource(R.drawable.green_regiscar);
									bt_ar_member.setBackgroundResource(R.drawable.black);
								}
								setArGroupOID(datasearch[position][19]);
								setArGroupDesc(datasearch[position][21]);
								
								tv_argroup.setText(getArGroupDesc());
								setProvinceCode(datasearch[position][12]);
								setProvinceName(datasearch[position][13]);
								tv_ar_province.setText(getProvinceName());
								setTelephone(datasearch[position][16]);
								tv_arphone.setText(getTelephone());
								setArName(datasearch[position][4]);
								tv_arname.setText(datasearch[position][4]);
								setVehicleRegistration(datasearch[position][55]);
								tv_idcar.setText(getVehicleRegistration());
								
								setCarGroupOID(datasearch[position][63]);
								setCarGroupName(datasearch[position][64]);
								tv_cargroup.setText(getCarGroupName());
								setCarSize(datasearch[position][60]);
								tv_carsize.setText(getCarSize());
								
								setCarBandOID(datasearch[position][54]);
								setCarBandName(datasearch[position][56]);
								
								tv_carband.setText(getCarBandName());
								
								setCarGenerationOID(datasearch[position][57]);
								setCarGenerationName(datasearch[position][61]); 
								tv_cargen.setText(getCarGenerationName());
								
								setCarColorOID(datasearch[position][59]);
								setColorName(datasearch[position][62]);
								tv_carcolor.setText(getColorName());
								
								setCarType(datasearch[position][58]);
							
							}
							
							break;
						case 2:
							// datacase_arname
							tv_arname.setText(datasearch[position][4]);
							setArName(datasearch[position][4]);
							break;
						case 3:
							// datacase_arphone
							tv_arphone.setText(datasearch[position][16]);
							setTelephone(datasearch[position][16]);
							break;
						case 4:
							// datacase_argroup
							setArGroupOID(_argroup[position][0].toString());
							setArGroupCode(_argroup[position][1].toString());
							setArGroupDesc(_argroup[position][2].toString()); 
							setArGroupMainCode(_argroup[position][3].toString()); 
							setArGroupMainDesc(_argroup[position][4].toString()); 
							tv_argroup.setText(getArGroupDesc());
							break;
						case 5:
							// datacase_province
							if(change){
								setProvinceCode(datasearch[position][0].toString());
								setProvinceName(datasearch[position][2].toString()); 
							}else{
								if (position < _provinc_favorit.length) {
									setProvinceCode(_provinc_favorit[position][0].toString());
									setProvinceName(_provinc_favorit[position][2].toString()); 
								} else if (position > _provinc_favorit.length) {
									setProvinceCode(_provinc_defalt[position - (_provinc_favorit.length + 1)][0].toString());
									setProvinceName(_provinc_defalt[position - (_provinc_favorit.length + 1)][2].toString()); 
								} 
							}
							tv_ar_province.setText(getProvinceName());
							break;
						case 6:
							// datacase_cartype
//							if(position == 0){
//								setCarType("C");
//								tv_cartype.setText("รถยนต์");
//							}else if(position == 1){
//								setCarType("M");
//								tv_cartype.setText("รถมอเตอร์ไซต์");
//							}
							break;
						case 7:
							// datacase_cargroup
							setCarGroupOID(_cargroup[position][0].toString());
							setCarGroupName(_cargroup[position][1].toString());
							setCarSize(_cargroup[position][2].toString());
							tv_cargroup.setText(getCarGroupName());
							tv_carsize.setText(getCarSize());
							if(_cargroup[position][1].toString().equals("มอเตอร์ไซต์")){
								setCarType("M");    
							}else{
								setCarType("C");
							}
//							Toast.makeText(getApplicationContext(), _cargroup[position][1]+","+getCarType(), Toast.LENGTH_SHORT).show();  
							break;
						case 8:
							// datacase_carsize
							if(position == 0){
								setCarSize("S");
							}else if(position == 1){
								setCarSize("M");
							}else if(position == 2){
								setCarSize("L");
							}else if(position == 3){
								setCarSize("XL");
							}
							tv_carsize.setText(getCarSize());
							break;
						case 9:
							// datacase_carband
							try{
								if (position <= _carbands_favorit.length) {
									setCarBandOID(_carbands_favorit[position][0].toString());
									setCarBandName(_carbands_favorit[position][2].toString());
								} else if (position > _carbands_favorit.length) {
									setCarBandOID(_carbands_defalt[position - (_carbands_favorit.length +1)][0].toString());
									setCarBandName(_carbands_defalt[position - (_carbands_favorit.length +1 )][2].toString());
								} else {
									setCarBandName("ไม่ระบุ");
								}
							}catch(Exception e){
								setCarBandName("ไม่ระบุ");
							}
							tv_cargen.setText("ไม่ระบุ");
							tv_carband.setText(getCarBandName());
							break;
						case 10:
							// datacase_cargen
							try {
								setCarGenerationOID(_cargenerations[position][0].toString());
								setCarGenerationName(_cargenerations[position][2].toString()); 
							} catch (Exception e) {
								setCarGenerationName("ไม่ระบุ");
							}
							tv_cargen.setText(getCarGenerationName());
							break;
						case 11:
							// datacase_carcolor
							setCarColorOID(_carcolor[position][0].toString());
							setColorName(_carcolor[position][2].toString());
							tv_carcolor.setText(getColorName());
							break;
						default:
							break;
		 
						}
						// TODO Auto-generated method stub
						imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
						DataDialog.dismiss();
					}
				});
				
				bt.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						switch (getDATACASE()) {
						case 0:
							// datacase_idar
							break;
						case 1:
							// datacase_idcar
							if(!et.getText().toString().equals("")){
								tv_idcar.setText(et.getText().toString());
								setVehicleRegistration(et.getText().toString());
							}
							break;
						case 2:
							// datacase_arname
							if(!et.getText().toString().equals("")){
								tv_arname.setText(et.getText().toString());
								setArName(et.getText().toString());
							}
							break;
						case 3:
							// datacase_arphone
							if(!et.getText().toString().equals("")){
								tv_arphone.setText(et.getText().toString());
								setTelephone(et.getText().toString());
							}
							break;
						case 4:
							// datacase_argroup
							break;
						case 5:
							// datacase_provinec
							break;
						case 6:
							// datacase_cartype
							break;
						case 7:
							// datacase_cargroup
							break;
						case 8:
							// datacase_carsize
							break;
						case 9:
							// datacase_carband
							break;
						case 10:
							// datacase_cargen
							break;
						case 11:
							// datacase_carcolor
							break;
						default:
							break;
		 
						}
						imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
						DataDialog.dismiss();
					}
				});
				
				et.addTextChangedListener(new TextWatcher() {
					public void afterTextChanged(Editable s) {
						// Abstract Method of TextWatcher Interface.
					}
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						// Abstract Method of TextWatcher Interface.
					}
					public void onTextChanged(CharSequence s, int start, int before,
							int count) {
						textlength = et.getText().length();
						mArrayAdapter.clear();
						switch (getDATACASE()) {
						case 0:
							// datacase_idar
							try {
								datasearch = ar.SelectAll_ArFF("","","");
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][1].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][1].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][1].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 1:
							// datacase_idcar
							try {
								datasearch = ar.SelectAll_ArFF("","","");
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][55].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][55].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][55].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 2:
							// datacase_arname
							try {
								datasearch = ar.SelectAll_ArFF("","","");
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][4].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][4].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][4].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 3:
							// datacase_arphone
							try {
								datasearch = ar.SelectAll_ArFF("","","");
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][16].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][16].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][16].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 4:
							// datacase_argroup
							try {
								datasearch = argroup.SelectAll_ArGroup(getArGroupMainOID());
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][2].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][2].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][2].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 5:
							// datacase_provinec
							
							try {
								datasearch = province.SelectAll_Addresses("");
								mArrayAdapter.clear();
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][2].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][2].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][2].toString());
										}
										change = true;
									}
								}
							} catch (Exception e) {
							}
							break;
						case 6:
							// datacase_cartype
							break;
						case 7:
							// datacase_cargroup
							try {
								datasearch = cargroup.SelectAll_CarGroup();
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][1].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][1].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][1].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						case 8:
							// datacase_carsize
							break;
						case 9:
							// datacase_carband
							break;
						case 10:
							// datacase_cargen
							break;
						case 11:
							// datacase_carcolor
							try {
								datasearch = carcolor.SelectAll_Colors();
								for (int i = 0; i < datasearch.length; i++) {
									if (textlength <= datasearch[i][2].length() && textlength>0) {
										if (et.getText()
												.toString()
												.equalsIgnoreCase(
														(String) datasearch[i][2].subSequence(
																0, textlength))) {
											mArrayAdapter.add(datasearch[i][2].toString());
										}
									}
								}
							} catch (Exception e) {
							}
							break;
						default:
							break;
		 
						}
						
					}
				});
			}
		});
		
		ImportDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
//				test();
				
				lv = (ListView) ImportDialog.findViewById(R.id.ListView0111);
				et = (EditText) ImportDialog.findViewById(R.id.EditText0111);
				mArrayAdapter = new ArrayAdapter<String>(CarCare_GetCar.this, android.R.layout.simple_list_item_1);
				lv.setAdapter(mArrayAdapter);
				final InputMethodManager imm = (InputMethodManager)getSystemService(
					      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
				lv.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View selectedItemView, int position,
							long id) {
						position = position+1;
						// TODO Auto-generated method stub
						tv_new.setVisibility(View.GONE);
						tv_edit.setVisibility(View.VISIBLE);
						Ismember = true;
						tv_idar.setText(datasearch[position][1]);
						setArCode(datasearch[position][1]);
						setAROID(datasearch[position][0]);
						setArGroupMainOID(datasearch[position][22]);
						setArGroupMainCode(datasearch[position][23]);
						setArGroupMainDesc(datasearch[position][24]);
						if(getArGroupMainOID().equals("116201309160002")){
							bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.vipmember);
							imgUser.setImageBitmap(bImage);
							imgUser.setScaleType(ScaleType.FIT_XY);
							bt_ar_general.setBackgroundResource(R.drawable.black);
							bt_ar_member.setBackgroundResource(R.drawable.green_regiscar);
						}else{
							bImage = BitmapFactory.decodeResource(imgUser.getResources(), R.drawable.logouser);
							imgUser.setImageBitmap(bImage);
							imgUser.setScaleType(ScaleType.FIT_XY);
							bt_ar_general.setBackgroundResource(R.drawable.green_regiscar);
							bt_ar_member.setBackgroundResource(R.drawable.black);
						}
						setArGroupOID(datasearch[position][19]);
						setArGroupDesc(datasearch[position][21]);
						tv_argroup.setText(getArGroupDesc());
						setProvinceCode(datasearch[position][12]);
						setProvinceName(datasearch[position][13]);
						tv_ar_province.setText(getProvinceName());
						setTelephone(datasearch[position][16]);
						tv_arphone.setText(getTelephone());
						setArName(datasearch[position][4]);
						tv_arname.setText(datasearch[position][4]);
						setVehicleRegistration(datasearch[position][55]);
						tv_idcar.setText(getVehicleRegistration());
						
						setCarGroupOID(datasearch[position][63]);
						setCarGroupName(datasearch[position][64]);
						tv_cargroup.setText(getCarGroupName());
						setCarSize(datasearch[position][60]);
						tv_carsize.setText(getCarSize());
						
						setCarBandOID(datasearch[position][54]);
						setCarBandName(datasearch[position][56]);
						
						tv_carband.setText(getCarBandName());
						
						setCarGenerationOID(datasearch[position][57]);
						setCarGenerationName(datasearch[position][61]); 
						tv_cargen.setText(getCarGenerationName());
						
						setCarColorOID(datasearch[position][59]);
						setColorName(datasearch[position][62]);
						tv_carcolor.setText(getColorName());
						
						setCarType(datasearch[position][58]);
					
						
						imm.hideSoftInputFromWindow(et.getWindowToken(), 0);	
						ImportDialog.dismiss();
					}
				});
				
				
				try {
					datasearch = ar.SelectAll_ArFF_ForImport("","","");
					for (int i = 0; i < datasearch.length; i++) {
						if(!datasearch[i][4].equals("") && !datasearch[i][4].equals("ไม่ระบุ")){
							mArrayAdapter.add(datasearch[i][4].toString());
						}
					}
				}catch(Exception e){
					
				}
					
				et.addTextChangedListener(new TextWatcher() {
					public void afterTextChanged(Editable s) {
						// Abstract Method of TextWatcher Interface.
					}

					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						// Abstract Method of TextWatcher Interface.
					}

					public void onTextChanged(CharSequence s, int start, int before,
							int count) {
						textlength = et.getText().length();
						mArrayAdapter.clear();
						try {
							datasearch = ar.SelectAll_ArFF("","","");
							for (int i = 0; i < datasearch.length; i++) {
								if (textlength <= datasearch[i][4].length() && textlength >0) {
									if (et.getText()
											.toString()
											.equalsIgnoreCase(
													(String) datasearch[i][4].subSequence(
															0, textlength))) {
										mArrayAdapter.add(datasearch[i][4].toString());
									}
								}
							}
							
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
		});
	
		// ed_idar.setText(datetime.getDateNowymd().toString()+datetime.getTimeNownosemi().toString());
	
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ar.setContext(getApplicationContext());
		servicepos.setContext(getApplicationContext());
		ffuser.setContext(getApplicationContext());
		argroup.setContext(getApplicationContext());
		province.setContext(getApplicationContext());
		cargroup.setContext(getApplicationContext());
		carband.setContext(getApplicationContext());
		cargenneration.setContext(getApplicationContext());
		carcolor.setContext(getApplicationContext());
		usergroup.setContext(getApplicationContext());
		Init();
		
	}

	public void Init() {
		// ---------Define----------------------//
		if(!MODE.equals("EDIT")){
			DEFINE_NEW();
			Define_ArFFOID();
			Define_POSDoc();
		}else{
			tv_new.setVisibility(View.GONE);
			tv_edit.setVisibility(View.VISIBLE);
			searchcar_button_clr.setBackgroundColor(Color.GRAY);
			searchcar_button_clr.setEnabled(false);
		}
		
		
	}

	
	public void Define_POSDoc(){
		String _DocNumber = "ssss";
		
		String number;
		int _Number = 0;
		try {
			String Number[][] = servicepos.SelectAll_ServicePOS("",
										getUserGroupCode()+TabletCode + DateTime.getdatetimeForDoc()
										,"");
			number = Number[Number.length-1][1].substring(9, 12);  
			_Number = Integer.valueOf(number)+1;
			
		} catch (Exception e) {
			_Number = 1;
//			Toast.makeText(getApplicationContext(), "EEEE", Toast.LENGTH_SHORT).show();
		}
		if (_Number < 10) {
			_DocNumber = "0000" + String.valueOf(_Number);
		} else if (_Number < 100) {
			_DocNumber = "000" + String.valueOf(_Number);
		} else if (_Number < 1000) {
			_DocNumber = "00" + String.valueOf(_Number);
		} else if (_Number < 10000) {
			_DocNumber = "0" + String.valueOf(_Number);
		}else if (_Number < 99999) {
			_DocNumber = String.valueOf(_Number);
		}else{
			_DocNumber = "max";
		}
		
		String posDocID = getUserGroupCode()+TabletCode + DateTime.getdatetimeForDoc() + _DocNumber;
		
		setPOSDocOID(posDocID);
		tv_idservice.setText(getPOSDocOID());
		tv_idservice.setTextColor(Color.BLACK);
	}
	public Boolean Create_POsService() {
		String Datetimenow = DateTime.getDateTimeNow().toString();
		String Timenow = DateTime.getTimeNow();
		String OID = DateTime.getDateNowymd().toString()
				+ DateTime.getTimeNownosemi().toString();
		long checkinsert;
		if(MODE.equals("EDIT")){
			checkinsert = servicepos.UpdateServicePOS(  getPOSDocOID(), 
					
														getArCode(), 
														getVehicleRegistration(), 
														
														getPayableDateTime(), 
														
														getFFUserCode(),
														Datetimenow, 
														"0");
			
		}else{
			String datatempArGroupMain[][] = null;
			try {
				datatempArGroupMain = argroupMain.SelectAll_ArGroupMain(getArGroupMainOID());
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			checkinsert = servicepos.InsertServicePOSOID(OID, 
					
														getPOSDocOID(), 
														getVehicleRegistration(),
														getArCode(), 
														getFFUserCode(), 
														Timenow, 
														
														getPayableDateTime(), 
														getUserGroupOID(),
														"รอรับบริการ", 
														Timenow, 
														"0.00", 
														
														"0.00", 
														"0.00", 
														"0.00", 
														"", 
														datatempArGroupMain[0][3],
														
														getFFUserCode(), 
														Datetimenow, 
														Datetimenow, 
														"0", 
														"0");
		}
		if (checkinsert > 0) {
			IsinsertService = true;
		} else {
			IsinsertService = false;
		}
		return  IsinsertService;
	}
	
	public void Define_ArFFOID() {
	
		String _DocNumber = "sss";
		String number;
		int _Number = 0;
		try {
			
				String data[][] = ar.SelectAll_ArFF("", "C"+getUserGroupCode()+getTabletCode(),"");
						
				number = data[data.length-1][1].substring(6, 10);  
				_Number = Integer.valueOf(number)+1;
//				Toast.makeText(getApplicationContext(), number, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			_Number = 1;
//			Toast.makeText(getApplicationContext(), "EEEE", Toast.LENGTH_SHORT).show();
		}
		if (_Number < 10) {
			_DocNumber = "000" + String.valueOf(_Number);
		} else if (_Number < 100) {
			_DocNumber = "00" + String.valueOf(_Number);
		} else if (_Number < 1000) {
			_DocNumber = "0" + String.valueOf(_Number);
		}else if (_Number < 9999) {
			_DocNumber = String.valueOf(_Number);
		}else if (_Number > 9999) {
			_DocNumber = "ssss";
		}
		
		String Ar_ID = "C"+getUserGroupCode()+TabletCode + _DocNumber;
		tv_idar.setText(Ar_ID);
		tv_idar.setTextColor(Color.BLACK);
		setArCode(Ar_ID);
	}
//	// ------------------------DEFINE------------------------------------------//
	public void DEFINE_NEW() {
		bt_ar_general.setBackgroundResource(R.drawable.green_regiscar);
		bt_ar_member.setBackgroundResource(R.drawable.black);
		Ismember = false;
		tv_new.setVisibility(View.VISIBLE);
		tv_edit.setVisibility(View.GONE);
		tv_idcar.setText("");
		tv_arname.setText("");
		tv_arphone.setText("");
		tv_cargen.setText("");
		tv_carcolor.setText("");
		tv_timewait.setText("รอ");
	
		setArGroupMainOID("116201309160001");
		
		setArGroupOID("115201309160001");
		setArGroupCode("1");
		setArGroupDesc("เงินสด"); 
		tv_argroup.setText(getArGroupDesc());
		setProvinceCode("500000");
		setProvinceName("เชียงใหม่"); 
		tv_ar_province.setText(getProvinceName());
		setCarType("C");
//		tv_cartype.setText("รถยนต์");
		setCarGroupOID("139201310070001");
		setCarGroupName("รถเก๋ง");
		tv_cargroup.setText(getCarGroupName());
		setCarSize("S");
		tv_carsize.setText(getCarSize());
		setCarBandOID("");
		setCarBandName("");
		tv_carband.setText(getCarBandName());
		tv_timewait.setText("รอ");
		setPayableDateTime("00:00");
		
	}

	private OnClickListener searchcar_enter = new OnClickListener() {
		public void onClick(View v) {
			new  ArFF().execute();
		}
	};

	private OnClickListener searchcar_cancle = new OnClickListener() {
		public void onClick(View v) {
			onBackPressed();
		}
	};
	private OnClickListener searchcar_clr = new OnClickListener() {
		public void onClick(View v) {
			Init();
		}
	};

	private OnClickListener importcar = new OnClickListener() {
		public void onClick(View v) {
			ImportDialog.show();
		}
	};
	
	private OnClickListener timewait = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Iswait=true;
			Calendar calendar = GregorianCalendar.getInstance();
			CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(CarCare_GetCar.this, timeSetListener, 
					calendar.get(Calendar.HOUR_OF_DAY), 
					calendar.get(Calendar.MINUTE), true);
			timePickerDialog.setTitle("เวลานัดหมาย");
			timePickerDialog.setIcon(R.drawable.timee);
			timePickerDialog.show();
		}
	};
	
	private OnClickListener timenotwait = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Iswait=false;
			setPayableDateTime("00:00");
			tv_timewait.setText("รอ");
		}
	};
	
	public static class CustomTimePickerDialog extends TimePickerDialog{
		 
        public static final int TIME_PICKER_INTERVAL=1;
        private boolean mIgnoreEvent=false;

        public CustomTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
        super(context, callBack, hourOfDay, minute, is24HourView);
        	
        }
 
        @Override
        public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
            super.onTimeChanged(timePicker, hourOfDay, minute);
            if (!mIgnoreEvent){
                minute = getRoundedMinute(minute);
                mIgnoreEvent=true;
                timePicker.setCurrentMinute(minute);
                mIgnoreEvent=false;
            }
        }
        
        public static  int getRoundedMinute(int minute){
             if(minute % TIME_PICKER_INTERVAL != 0){
                int minuteFloor = minute - (minute % TIME_PICKER_INTERVAL);
                minute = minuteFloor + (minute == minuteFloor + 1 ? TIME_PICKER_INTERVAL : 0);
                if (minute == 60)  minute=0;
             }
            return minute;
        }
    }
	
	private CustomTimePickerDialog.OnTimeSetListener timeSetListener = new CustomTimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        	tv_timewait.setEnabled(true);
        	tv_timewait.setBackgroundColor(Color.WHITE);
			tv_timewait.setText(String.format("%02d", hourOfDay) + ":" +String.format("%02d", minute));
            setPayableDateTime(tv_timewait.getText().toString());
			Iswait=true;
        }
        
        
	};

	private OnClickListener text_clrsr = new OnClickListener() {
        public void onClick(View v) {
        	tv_callnumber.setText("");
        }
    };
    private OnClickListener text_0 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"0");
        }
    };
    private OnClickListener text_1 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"1");
        }
    };
    private OnClickListener text_2 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"2");
        }
    };
    private OnClickListener text_3 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"3");
        }
    };
    private OnClickListener text_4 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"4");
        }
    };
    private OnClickListener text_5 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"5");
        }
    };
    private OnClickListener text_6 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"6");
        }
    };
    private OnClickListener text_7 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"7");
        }
    };
    private OnClickListener text_8 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"8");
        }
    };
    private OnClickListener text_9 = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	tv_callnumber.setText(tmp+"9");
        }
    };
    private OnClickListener text_cancle = new OnClickListener() {
        public void onClick(View v) {
        	PhoneDialog.dismiss();
        }
    };
    private OnClickListener text_del = new OnClickListener() {
        public void onClick(View v) {
        	String tmp = tv_callnumber.getText().toString();
        	int temp = tmp.length();
    		if(temp==1){
    			tv_callnumber.setText("");
    		}else{
    			tv_callnumber.setText(tmp.subSequence(0, temp-1));
    		}
        }
    };
    private OnClickListener text_enter = new OnClickListener() {
        public void onClick(View v) {
        	tv_arphone.setText(tv_callnumber.getText().toString());
			setTelephone(tv_callnumber.getText().toString());
			PhoneDialog.dismiss();
        }
    };
    
	//  Exit
	@Override
	public void onBackPressed() {

		new AlertDialog.Builder(this)
				.setTitle("ยกเลิก")
				.setIcon(R.drawable.erroralert)
				.setMessage("ต้องการยกเลิกการทำรายการ")
				.setNegativeButton(android.R.string.yes,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								finish();
							}
						})
				.setPositiveButton(android.R.string.no,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {

							}
						}).create().show();
	}

	// --------------------------GET SET -----------------------------------//
	
	 public String getArGroupMainOID() {
		return ArGroupMainOID;
	}

	public void setArGroupMainOID(String arGroupMainOID) {
		ArGroupMainOID = arGroupMainOID;
	}

	public String getArGroupOID() {
		return ArGroupOID;
	}

	public void setArGroupOID(String arGroupOID) {
		ArGroupOID = arGroupOID;
	}

	public String getCarGroupOID() {
		return CarGroupOID;
	}

	public void setCarGroupOID(String carGroupOID) {
		CarGroupOID = carGroupOID;
	}

	public String getCarBandOID() {
		return CarBandOID;
	}

	public void setCarBandOID(String carBandOID) {
		CarBandOID = carBandOID;
	}

	public String getCarGenerationOID() {
		return CarGenerationOID;
	}

	public void setCarGenerationOID(String carGenerationOID) {
		CarGenerationOID = carGenerationOID;
	}

	public String getCarColorOID() {
		return CarColorOID;
	}

	public void setCarColorOID(String carColorOID) {
		CarColorOID = carColorOID;
	}

	public String getArCode() {
		return ArCode;
	}

	public void setArCode(String arCode) {
		ArCode = arCode;
	}

	public String getArTitle() {
		return ArTitle;
	}

	public void setArTitle(String arTitle) {
		ArTitle = arTitle;
	}

	public String getArName() {
		return ArName;
	}

	public void setArName(String arName) {
		ArName = arName;
	}

	public String getArNickName() {
		return ArNickName;
	}

	public void setArNickName(String arNickName) {
		ArNickName = arNickName;
	}

	public String getArGroupDesc() {
		return ArGroupDesc;
	}

	public void setArGroupDesc(String arGroupDesc) {
		ArGroupDesc = arGroupDesc;
	}

	public String getFFUserName() {
		return FFUserName;
	}

	public void setFFUserName(String fFUserName) {
		FFUserName = fFUserName;
	}

	public String getArGroupMainCode() {
		return ArGroupMainCode;
	}

	public void setArGroupMainCode(String arGroupMainCode) {
		ArGroupMainCode = arGroupMainCode;
	}

	public String getArGroupMainDesc() {
		return ArGroupMainDesc;
	}

	public void setArGroupMainDesc(String arGroupMainDesc) {
		ArGroupMainDesc = arGroupMainDesc;
	}



	public String getProvinceCode() {
		return ProvinceCode;
	}

	public void setProvinceCode(String provinceCode) {
		ProvinceCode = provinceCode;
	}

	public String getProvinceName() {
		return ProvinceName;
	}

	public void setProvinceName(String provinceName) {
		ProvinceName = provinceName;
	}


	public String getArGroupCode() {
		return ArGroupCode;
	}

	public void setArGroupCode(String arGroupCode) {
		ArGroupCode = arGroupCode;
	}


	public String getTelephone() {
		return Telephone;
	}

	public void setTelephone(String telephone) {
		Telephone = telephone;
	}


	public String getMobile() {
		return Mobile;
	}

	public void setMobile(String mobile) {
		Mobile = mobile;
	}

	public String getFFSaleCode() {
		return FFSaleCode;
	}

	public void setFFSaleCode(String fFSaleCode) {
		FFSaleCode = fFSaleCode;
	}

	public String getFFUserCode() {
		return FFUserCode;
	}

	public void setFFUserCode(String fFUserCode) {
		FFUserCode = fFUserCode;
	}

	public String getPicPath() {
		return PicPath;
	}

	public void setPicPath(String picPath) {
		PicPath = picPath;
	}

	public String getFFCashier() {
		return FFCashier;
	}

	public void setFFCashier(String fFCashier) {
		FFCashier = fFCashier;
	}

	public String getVehicleRegistration() {
		return VehicleRegistration;
	}

	public void setVehicleRegistration(String vehicleRegistration) {
		VehicleRegistration = vehicleRegistration;
	}

	public String getCarType() {
		return CarType;
	}

	public void setCarType(String carType) {
		CarType = carType;
	}

	public String getColorOID() {
		return ColorOID;
	}

	public void setColorOID(String colorOID) {
		ColorOID = colorOID;
	}

	public String getCarSize() {
		return CarSize;
	}

	public void setCarSize(String carSize) {
		CarSize = carSize;
	}

	public String getCompanyOID() {
		return CompanyOID;
	}

	public void setCompanyOID(String companyOID) {
		CompanyOID = companyOID;
	}


	public String getFFUserOID() {
		return FFUserOID;
	}

	public void setFFUserOID(String fFUserOID) {
		FFUserOID = fFUserOID;
	}

	public String getDepCode() {
		return DepCode;
	}

	public void setDepCode(String depCode) {
		DepCode = depCode;
	}

	public String getUserGroupOID() {
		return UserGroupOID;
	}

	public void setUserGroupOID(String userGroupOID) {
		UserGroupOID = userGroupOID;
	}

	public String getTabletCode() {
		return TabletCode;
	}

	public void setTabletCode(String tabletCode) {
		TabletCode = tabletCode;
	}

	public String getPOSDocOID() {
		return POSDocOID;
	}

	public void setPOSDocOID(String pOSDocOID) {
		POSDocOID = pOSDocOID;
	}

	public String getCarGenerationName() {
		return CarGenerationName;
	}

	public void setCarGenerationName(String carGenerationName) {
		CarGenerationName = carGenerationName;
	}

	public String getColorName() {
		return ColorName;
	}

	public void setColorName(String colorName) {
		ColorName = colorName;
	}

	public String getCarGroupName() {
		return CarGroupName;
	}

	public void setCarGroupName(String carGroupName) {
		CarGroupName = carGroupName;
	}

	public String getCarBandName() {
		return CarBandName;
	}

	public void setCarBandName(String carBandName) {
		CarBandName = carBandName;
	}

	public String getDatetimenow() {
		return Datetimenow;
	}

	public void setDatetimenow(String datetimenow) {
		Datetimenow = datetimenow;
	}

	public String getOID() {
		return OID;
	}

	public void setOID(String oID) {
		OID = oID;
	}

	public Boolean getIsmember() {
		return Ismember;
	}

	public void setIsmember(Boolean ismember) {
		Ismember = ismember;
	}

	public Boolean getIsinsertService() {
		return IsinsertService;
	}

	public void setIsinsertService(Boolean isinsertService) {
		IsinsertService = isinsertService;
	}

	public Boolean getIsinsertAr() {
		return IsinsertAr;
	}

	public void setIsinsertAr(Boolean isinsertAr) {
		IsinsertAr = isinsertAr;
	}

	public Boolean getIswait() {
		return Iswait;
	}

	public void setIswait(Boolean iswait) {
		Iswait = iswait;
	}
	
	public String getPayableDateTime() {
		return PayableDateTime;
	}

	public void setPayableDateTime(String payableDateTime) {
		PayableDateTime = payableDateTime;
	}

	public String getArStatus() {
		return ArStatus;
	}

	public void setArStatus(String arStatus) {
		ArStatus = arStatus;
	}

	@Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case DIALOG_DOWNLOAD_PROGRESS:
	            mProgressDialog = new ProgressDialog(this);
	            mProgressDialog.setMessage("Checking.....");
	            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	            mProgressDialog.setCancelable(true);
	            mProgressDialog.show();
	            return mProgressDialog;
	        default:
	            return null;
	        }
	    }
	 	//-----------AsyncTask-Loading----------------------------------//
	    public class ArFF extends AsyncTask<String, Void, Void> {
			protected void onPreExecute() {
	        	super.onPreExecute();
//	        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
	        	setOID(DateTime.getDateNowymd().toString()
	    				+ DateTime.getTimeNownosemi().toString());
	    		setDatetimenow(DateTime.getDateTimeNow().toString());
	        }
	        
			@Override
	        protected Void doInBackground(String... params) {
				try{
					if(!Ismember){
						
						long checkinsert = ar.InsertArFF( 
								getOID(), 
								
								getArCode(),
								getArName(), 
								getArName(), 
								getProvinceCode(), 
								getProvinceName(), 
								getTelephone(), 
								getTelephone(), 
								getArGroupOID(), 
								getArGroupCode(),
								getArGroupDesc(), 
								getArGroupMainOID(), 
								
								getArGroupMainCode(), 
								getArGroupMainDesc(), 
								getFFUserCode(), 
								getFFUserName(), 
								getFFUserCode(),
								
								getFFUserCode(), 
								getPicPath(),
								getArStatus(),
								getCarBandOID(), 
								getVehicleRegistration(),

								getCarBandName(), 
								getCarGenerationOID(), 
								getCarType(), 
								getCarColorOID(), 
								getCarSize(), 
								
								getCarGenerationName(), 
								getColorName(), 
								getCarGroupOID(), 
								getCarGroupName(),
								
								getFFUserCode(), 
								Datetimenow, 
								Datetimenow, 
								"0", 
								"0");
						if (checkinsert > 0) {
//							setPOSDocOID(Ar_ID);
							IsinsertAr = true;
						} else {
							IsinsertAr = false;
						}
					}else{
						long checkupdate = ar.UpdateArFF(
								getAROID(), 
								getArCode(), 
								getArName(), 
								getProvinceCode(), 
								getProvinceName(), 
								getTelephone(),
								
								getTelephone(), 
								getArGroupOID(), 
								getArGroupCode(),
								getArGroupDesc(), 
								getArGroupMainOID(), 
								
								getArGroupMainCode(), 
								getArGroupMainDesc(), 
								getFFUserCode(), 
								getFFUserName(), 
								getFFUserCode(), 
								
								getFFUserCode(), 
								getPicPath(),
								getArStatus(),
								getCarBandOID(), 
								getVehicleRegistration(), 
								
								getCarBandName(), 
								getCarGenerationOID(), 
								getCarType(), 
								getCarColorOID(), 
								getCarSize(), 
								
								getCarGenerationName(), 
								getColorName(), 
								getCarGroupOID(), 
								getCarGroupName(),
								
								getFFUserCode(), 
								Datetimenow, 
								"0");
						if (checkupdate > 0) {
//							setPOSDocOID(Ar_ID);
							IsinsertAr = true;
						} else {
							IsinsertAr = false;
						}
					}
				}catch(Exception e){
				}
	    		return null;
	        }

			protected void onPostExecute(Void unused) {
//				Toast.makeText(CarCare_GetCar.this, String.valueOf(Ismember), Toast.LENGTH_SHORT).show();
	        	if(IsinsertAr){
	    			if (Create_POsService()) {
	    				if(!MODE.equals("EDIT")){
	    					Intent POS = new Intent(CarCare_GetCar.this,
		    						Carcare_Service.class);
		    				POS.putExtra("FFUserOID", getFFUserOID());// UserOID
		    				POS.putExtra("ArCode", getArCode());// ArCode
		    				POS.putExtra("CarSize", getCarSize());// CarSize
		    				POS.putExtra("CarGroupOID", getCarGroupOID());// CarGroupOID
		    				POS.putExtra("CarGroup", getCarGroupName());
		    				POS.putExtra("POSDocOID", getPOSDocOID());// POSDocOID
		    				startActivity(POS);
	    				}
	    				finish();
	    			} else {
	    				Toast.makeText(CarCare_GetCar.this, "ทำรายการ Service ล้มเหลว  !",
	    						Toast.LENGTH_SHORT).show();
	    			}
	        	}else{
	        		Toast.makeText(CarCare_GetCar.this, "ทำรายการ Ar ล้มเหลว  !",
							Toast.LENGTH_SHORT).show();
	        	}
	        } 
	    }
	    
		public String getUserGroupCode() {
			return UserGroupCode;
		}

		public void setUserGroupCode(String userGroupCode) {
			UserGroupCode = userGroupCode;
		}

		public int getDATACASE() {
			return DATACASE;
		}

		public void setDATACASE(int dATACASE) {
			DATACASE = dATACASE;
		}

		public String getAROID() {
			return AROID;
		}

		public void setAROID(String aROID) {
			AROID = aROID;
		}
	 
	
}
